<template>
  <div class="materwarpper">
    <div class="pageheader flex aligncenter">
      <svg-icon icon-class="icircleleft" class-name="leftarr f-22 mr-12 commhover" @click="handleBack" />
      <span class="f-14 fw-6"> 新建素材</span>
    </div>
    <div class="addbody flexcolumn">
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        label-position="left"
        class="formbody f-14"
      >
        <div class="bg_fff formbox mb-12">
          <div class="form_header">基本信息</div>
          <div class="form_body">
            <el-form-item label="素材标题：" prop="title">
              <el-input
                v-model="form.title"
                style="width: 90%"
                maxlength="30"
                placeholder="请为素材命名，便于识别，最多30字"
              ></el-input>
            </el-form-item>
            <el-form-item label="素材标签：" prop="name">
              <el-autocomplete
                v-model="form.name"
                style="width: 90%"
                :fetch-suggestions="querySearch"
                @keyup.enter.native="handleAddLable"
                placeholder="新建或搜索标签，回车键确认"
              ></el-autocomplete>
              <div v-if="form.labels.length" class="labelbox mt-15">
                <div
                  class="labelitem c_text ml-5 mb-5"
                  v-for="(item, index) in form.labels"
                  :key="index"
                >
                  {{ item.tagName }}
                  <i
                    class="el-icon-close ml-10 commhover"
                    @click="removeLable(index)"
                  ></i>
                </div>
              </div>
            </el-form-item>
          </div>
        </div>
        <div class="bg_fff formbox mb-12">
          <div class="form_header">素材内容</div>
          <div class="form_body">
            <el-form-item label="内容：" prop="title">
              <material-content ref="material" />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="addfooter flexcenter">
      <el-button size="small" @click="handleBack">取消</el-button>
      <el-button size="small" type="primary" @click="handleSumbit">{{ submitText }}</el-button>
    </div>
  </div>
</template>

<script>
import {
  fetchMeterialTags,
  createMeterialTag,
  createMeterial,
  updateMeterial,
  fetchMeterialDetailById
} from "@/api/market/material";
import MaterialContent from "@/components/MaterialContent";
export default {
  data() {
    return {
      form: {
        title: "",
        name: "",
        labels: [],
      },
      rules: {},
      open: false,
      subloading: false,
      labelList: [],
      submitText: '完成创建'
    };
  },
  components: {
    MaterialContent,
  },
  mounted() {
    let meterialId = this.$route.query.id
    let type = this.$route.query.type
    if (meterialId) {
      this.fetchMeterialDetail(meterialId)
    }
    this.fetchMeterialTagList()
    if(meterialId && !type) {
      this.submitText = '完成编辑'
    }
  },
  methods: {
    // 获取素材标签列表
    async fetchMeterialTagList() {
      try {
        let data = await fetchMeterialTags()
        if (data.code === 200) {
          this.labelList = data?.rows || []
          return data?.rows
        }
      } catch (error) {
        this.$message.error("系统异常");
      }
    },

    async fetchMeterialDetail(meterialId){
      try {
        let result = await fetchMeterialDetailById(meterialId)
        if (result.code === 200) {
          this.form = {
            title: result.data.meterialName,
            labels: result.data.tagList,
          }
          this.$refs.material.messageList = result.data.contentList.map(item => ({...item, type: item.contentType}))
        }
      } catch (error) {
        
      }
      
    },

    querySearch(queryString, cb) {
      let results = []
      if (queryString) {
        const findout = this.labelList.filter(this.createFilter(queryString))
        results = findout.map(x => ({...x, value: x.tagName}))
      } else {
        results = this.labelList.map(x => ({...x, value: x.tagName}))
      }
      cb(results);
    },

    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.tagName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

    async handleAddLable() {
      if (this.form.name) {
        if (this.form.labels.includes(this.form.name)) {
          this.$message.warning("标签重复");
          return;
        }
        await this.onCreateMeterialTag(this.form.name)
        this.form.name = "";
      }
    },

    async onCreateMeterialTag(tagName) {
      let result = this.labelList.find(item => item?.tagName === tagName)
      if (!result) {
        await createMeterialTag({tagName})
        let result = await this.fetchMeterialTagList()
        let rowItem = result.find(item => item?.tagName === tagName)
        this.form.labels.push(rowItem)
      }else {
        this.form.labels.push(result)
      }
    },

    removeLable(index) {
      this.form.labels.splice(index, 1);
    },

    handleBack(){
      this.$router.back()
    },

    async handleSumbit(){
      let meterialId = this.$route.query.id
      let type = this.$route.query.type
      let meterialType = this.$route.query.list_type
      let context = this.$refs.material.messageList
      if (context.length === 0) {
        this.$message.error("素材内容不为空")
        return
      }
      let data = {
        meterialType,
        meterialName: this.form.title,
        tagIds: this.form.labels.map(item => (item.id)).toString(),
        contentList: this.$refs.material.messageList
      }
      if (meterialId && !type) {
        data.id = meterialId
        await updateMeterial(data)
      } else {
        await createMeterial(data)
      }
      this.handleBack()
    },
  },
};
</script>

<style lang="scss" scoped>
.materwarpper {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
}
.leftarr {
  color: #4b5a95;
}
.pageheader {
  line-height: 46px;
}
.addbody {
  height: calc(100% - 46px);
  padding: 20px 0;
}
.formbody {
  width: 1000px;
  overflow: auto;
  margin: 0 auto 12px;
}
.formbox {
  border-radius: 4px;
  border: 1px solid #e9e9e9;
}
.form_header {
  padding: 14px 24px;
  border-bottom: 1px solid #e9e9e9;
}
.form_body {
  padding: 24px;
}
.labelbox {
  border: 1px solid rgb(240, 240, 240);
  padding: 8px;
}
.labelitem {
  display: inline-block;
  border: 1px solid #d9d9d9;
  background-color: #f5f5f5;
  padding: 4px 13px;
  line-height: 22px;
}
.addfooter {
  box-shadow: 0 -4px 4px 0 rgba(0, 0, 0, 0.05);
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 56px;
  line-height: 56px;
  background: #fff;
}
</style>
